/*
 * Thread.cpp
 *
 *  Created on: Sep 20, 2016
 *      Author: root
 */

#include "yThread.h"
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
Thread::Thread(void (*func)(Thread*)) :
		thread() {
	fCallback = func;
	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);
}

void* Thread::createThread(void* arg) {
	Thread* t = (Thread*) arg;
	t->fCallback(t);
	return NULL;
}
void Thread::sleep(long t) {
	struct timeval now;
	struct timespec outtime;
	pthread_mutex_lock(&mutex);
	gettimeofday(&now, NULL);
	int sec = t / 1000;
	long usec = t % 1000 * 1000 * 1000;
	outtime.tv_sec = now.tv_sec + sec;
	outtime.tv_nsec = now.tv_usec * 1000 + usec;
	pthread_cond_timedwait(&cond, &mutex, &outtime);
	pthread_mutex_unlock(&mutex);
}
void Thread::start() {
	pthread_create(&thread, NULL, &Thread::createThread, this);
}
Thread::~Thread() {
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
}

